<template>
    <!-- 弹窗组件 -->
    <div class="dialog-box">
        <el-dialog v-model="dialogVisible" title="选择产品" width="1300">
            <div class="dialog-content">
                <!-- 分组区域保持不变 -->
                <!-- <div class="row-1">
                <div class="row-1-title">
                   <div>产品分组</div>
                   <div style="cursor: pointer">
                      <el-icon><Search /></el-icon>
                   </div>
                </div>
                <div
                   class="row-1-content"
                   v-for="item in 5"
                   :key="item"
                >
                   <div>分组{{ item }}</div>
                </div>
             </div> -->

                <!-- 左侧产品列表 -->
                <div class="row-2">
                    <div class="row-2-search">
                        <el-input placeholder="请输入关键字" suffix-icon="Search" />
                    </div>
                    <div class="table-container">
                        <el-table ref="leftTableRef" :data="tableData" style="width: 100%" border
                            @selection-change="handleSelectionChange" :row-key="(row: User) => row.id">
                            <el-table-column type="selection" width="55" />
                            <el-table-column label="产品名称" width="auto">
                                <template #default="scope">{{ scope.row.name }}</template>
                            </el-table-column>
                            <el-table-column prop="no" label="编号" width="auto" />
                            <el-table-column prop="specification" label="规格型号" show-overflow-tooltip width="auto" />
                            <el-table-column prop="measure_unit_name" label="采购单位" width="auto" />
                            <el-table-column prop="open_unit_name" label="拆零" width="auto" />
                            <el-table-column prop="spu_measure_unit_name" label="规格单位" width="auto" />
                            <el-table-column prop="specification" label="库存数量" width="auto" />
                            <el-table-column prop="price" label="单价" width="auto" />                       
                            <el-table-column  label="供应商" width="auto" >
                                <template #default="scope">{{ scope.row.suppliers.map(item => item.name).join(',') }}</template> 
                            </el-table-column>
                        </el-table>
                    </div>
                </div>

                <!-- 右侧已选产品列表 -->
                <div class="row-3">
                    <div class="row-head">
                        <div class="row-head-left">已选{{ rightCount }}项</div>
                        <div class="row-head-right" @click="clearAll" v-if="rightCount > 0">
                            清空
                        </div>
                    </div>
                    <div class="table-container">
                        <el-table :data="rightTableData" style="width: 100%">
                            <el-table-column prop="name" label="产品名称" width="auto" />
                            <el-table-column prop="no" label="编号" width="auto" />
                            <el-table-column prop="specification" label="规格型号" show-overflow-tooltip width="auto" />
                            <el-table-column prop="measure_unit_name" label="采购单位" width="auto" />
                            <el-table-column prop="open_unit_name" label="拆零" width="auto" />
                            <el-table-column prop="spu_measure_unit_name" label="规格单位" width="auto" />
                            <el-table-column prop="specification" label="库存数量" width="auto" />
                            <el-table-column prop="price" label="单价" width="auto" />                       
                            <el-table-column prop="price" label="供应商" width="auto" >
                                <template #default="scope">{{ scope.row.suppliers.map(item => item.name).join(',') }}</template> 
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button color="#626aef" @click="submit">确认</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import api from "@/api";
import { ref, computed, nextTick } from "vue";
import { Search } from "@element-plus/icons-vue";
import type { ElTable } from "element-plus";
// 产品列表数据类型
interface User {
    id: number;
    name: string;
    no: string;
    specification: string;
    measure_unit_name: string;
    open_unit_name: string; 
    spu_measure_unit_name: string;
    count: number;
    price: number;
    discount: number;
    discountPrice: number;
    totalAmount: number;
    suppliers?: any[]; // 供应商数组
    // 新增：API实际返回的字段
    stock?: number | string; // 库存
    open_unit_id?: number | string; // 拆零单位ID
    spu_unit_id?: number | string; // SPU单位ID
    spu_unit_name?: string; // SPU单位名称
    unit_num?: number | string; // 单位转换数量
    measure_unit_id?: number | string; // 采购单位ID
    spu_measure_unit_id?: number | string; // SPU采购单位ID
    img?: string; // 产品图片
    spu_id?: number | string; // SPU ID
    open_unit_num?: number | string; // 拆零数量
}

const tableData = ref<User[]>([]);//左侧产品表格数据
const currentSpuId = ref<number | null>(null); // 当前选择的SPU ID
const currentWarehouseId = ref<string | number | null>(null); // 当前仓库ID
const currentCustomerId = ref<string | number | null>(null); // 当前客户ID
// 获取产品列表
const getProductList = async () => {
    try {
        console.log('获取产品列表，参数:', {
            spu_id: currentSpuId.value,
            warehouse_id: currentWarehouseId.value,
            customer_id: currentCustomerId.value
        });

        const params: any = {};
        
        // 如果有SPU ID，添加到参数中
        if (currentSpuId.value) {
            params.spu_id = currentSpuId.value;
        }
        
      

        const res = await api.publicFun.getProductList(params);
        
        if (res.code === 200) {
            tableData.value = res.data;
            console.log('产品列表获取成功，数量:', res.data.length);
        } else {
            console.error('获取产品列表失败:', res.message);
            tableData.value = [];
        }
    } catch (error) {
        console.error('获取产品列表异常:', error);
        tableData.value = [];
    }
}

// 使用唯一标识name作为选中项的key
const selectedKeys = ref<Set<number>>(new Set());
const leftTableRef = ref<InstanceType<typeof ElTable>>();

// 右侧表格数据：从tableData中过滤出选中的项
const rightTableData = computed(() => tableData.value.filter((item) => selectedKeys.value.has(item.id)));

const rightCount = computed(() => selectedKeys.value.size);

// 处理左侧表格选中变化
function handleSelectionChange(selection: User[]) {
    console.log('🔄 handleSelectionChange 被触发');
    console.log('当前isInitializing状态:', isInitializing.value);
    console.log('selection参数:', selection.map(s => ({ id: s.id, name: s.name })));
    
    // 如果正在初始化，不要更新selectedKeys
    if (isInitializing.value) {
        console.log('🚫 正在初始化，跳过选中变化处理');
        return;
    }
    
    const newSelectedIds = selection.map((item) => Number(item.id));
    console.log('用户手动选中的新ID数组:', newSelectedIds);
    
    selectedKeys.value = new Set(newSelectedIds);
    console.log('👆 selectedKeys已更新为:', Array.from(selectedKeys.value));
}

// 更新左侧表格选中状态
function updateLeftTableSelection() {
    console.log('=== 开始更新表格选中状态 DEBUG ===');
    
    const table = leftTableRef.value;
    if (!table) {
        console.error('❌ 表格引用不存在');
        return;
    }
    
    if (tableData.value.length === 0) {
        console.warn('⚠️ 表格数据为空，跳过选中更新');
        return;
    }
    
    console.log('当前selectedKeys Set:', Array.from(selectedKeys.value));
    console.log('selectedKeys Set大小:', selectedKeys.value.size);
    console.log('表格数据数量:', tableData.value.length);
    
    // 先清空所有选中状态
    table.clearSelection();
    console.log('✅ 已清空表格选中状态');
    
    // 详细处理每一个要选中的ID
    const selectedIdsArray = Array.from(selectedKeys.value);
    console.log('需要选中的ID数组:', selectedIdsArray);
    
    let successCount = 0;
    let failCount = 0;
    
    // 遍历每个需要选中的ID
    selectedIdsArray.forEach((targetId, index) => {
        console.log(`\n--- 处理第${index + 1}个ID: ${targetId} ---`);
        
        // 在表格数据中查找对应的行
        const matchingRow = tableData.value.find(row => {
            const rowId = Number(row.id);
            const matches = rowId === targetId;
            console.log(`  比较 row.id(${row.id}) -> ${rowId} === ${targetId} = ${matches}`);
            return matches;
        });
        
        if (matchingRow) {
            console.log(`  ✅ 找到匹配行: ${matchingRow.name} (ID: ${matchingRow.id})`);
            try {
                table.toggleRowSelection(matchingRow, true);
                successCount++;
                console.log(`  ✅ 选中成功: ${matchingRow.name}`);
            } catch (error) {
                console.error(`  ❌ 选中失败: ${matchingRow.name}`, error);
                failCount++;
            }
        } else {
            console.log(`  ❌ 未找到ID为 ${targetId} 的产品行`);
            failCount++;
        }
    });
    
    console.log(`\n=== 选中操作汇总 ===`);
    console.log(`目标选中数量: ${selectedKeys.value.size}`);
    console.log(`成功选中数量: ${successCount}`);
    console.log(`失败数量: ${failCount}`);
    
    // 延迟验证最终结果
    setTimeout(() => {
        const finalSelection = table.getSelectionRows();
        console.log('\n=== 最终验证结果 ===');
        console.log(`最终选中数量: ${finalSelection.length}`);
        console.log('最终选中的产品详情:');
        finalSelection.forEach((product, idx) => {
            console.log(`  ${idx + 1}. ${product.name} (ID: ${product.id})`);
        });
        
        if (finalSelection.length !== selectedKeys.value.size) {
            console.warn(`⚠️ 选中数量不匹配！`);
            console.warn(`预期: ${selectedKeys.value.size}, 实际: ${finalSelection.length}`);
            
            // 检查哪些ID没有被选中
            const finalSelectedIds = new Set(finalSelection.map(p => Number(p.id)));
            selectedKeys.value.forEach(targetId => {
                if (!finalSelectedIds.has(targetId)) {
                    console.warn(`  缺失的ID: ${targetId}`);
                    const missingRow = tableData.value.find(r => Number(r.id) === targetId);
                    if (missingRow) {
                        console.warn(`  尝试补选: ${missingRow.name}`);
                        table.toggleRowSelection(missingRow, true);
                    }
                }
            });
        } else {
            console.log('✅ 所有产品选中状态正确');
        }
    }, 150);
}

// 移除单行
function removeRow(row: User) {
    selectedKeys.value.delete(row.id);
    selectedKeys.value = new Set(selectedKeys.value); // 触发响应式更新
    nextTick(() => {
        const table = leftTableRef.value;
        if (!table) return;
        table.toggleRowSelection(row, false);
    });
}

// 清空所有
function clearAll() {
    selectedKeys.value.clear();
    selectedKeys.value = new Set(); // 触发响应式更新
    nextTick(() => {
        const table = leftTableRef.value;
        if (!table) return;
        table.clearSelection();
    });
}

// 打开弹窗
const dialogVisible = ref(false);
const isInitializing = ref(false); // 新增：用于控制初始化状态
const openLoading = async (spuId?: number | null, warehouseId?: string | number | null, existingIds?: number[], customerId?: string | number | null) => {
    console.log('=== 打开产品选择弹窗 DEBUG ===');
    console.log('原始参数 existingIds:', existingIds);
    console.log('existingIds 是否为数组:', Array.isArray(existingIds));
    console.log('existingIds 长度:', existingIds?.length);
    
    // 设置初始化标志，防止选中事件干扰
    isInitializing.value = true;
    
    // 设置当前SPU ID和仓库ID
    currentSpuId.value = spuId || null;
    currentWarehouseId.value = warehouseId || null;
    currentCustomerId.value = customerId || null;
    // 详细处理已选中的产品ID数组
    let preSelectedIds: number[] = [];
    if (existingIds && Array.isArray(existingIds)) {
        console.log('开始处理产品ID数组:');
        existingIds.forEach((id, index) => {
            console.log(`  第${index + 1}个ID: ${id} (类型: ${typeof id})`);
            const numericId = Number(id);
            if (!isNaN(numericId)) {
                preSelectedIds.push(numericId);
                console.log(`    ✅ 转换成功: ${numericId}`);
            } else {
                console.log(`    ❌ 转换失败: ${id}`);
            }
        });
    }
    
    console.log('最终预选ID数组:', preSelectedIds);
    console.log('预选ID数组长度:', preSelectedIds.length);
    
    // 显示弹窗
    dialogVisible.value = true;
    
    try {
        // 获取产品列表
        await getProductList();
        console.log('产品列表获取完成，数量:', tableData.value.length);
        console.log('产品列表中的ID:', tableData.value.map(p => ({ id: p.id, name: p.name })));
        
        // 等待DOM更新
        await nextTick();
        
        // 设置选中的产品ID到Set中
        selectedKeys.value = new Set(preSelectedIds);
        console.log('Set创建完成，内容:', Array.from(selectedKeys.value));
        console.log('Set大小:', selectedKeys.value.size);
        
        // 验证每个预选ID是否在产品列表中存在
        preSelectedIds.forEach(id => {
            const found = tableData.value.find(p => Number(p.id) === id);
            console.log(`ID ${id} 在产品列表中${found ? '存在' : '不存在'}:`, found ? found.name : 'N/A');
        });
        
        // 再等待一个tick
        await nextTick();
        
        // 更新表格选中状态
        updateLeftTableSelection();
        
        // 延迟结束初始化状态
        setTimeout(() => {
            isInitializing.value = false;
            console.log('🎯 初始化完成，恢复正常选中监听');
        }, 300);
        
    } catch (error) {
        console.error('打开产品选择弹窗失败:', error);
        isInitializing.value = false;
    }
};

const submit = () => {
    if (rightTableData.value.length > 0) {
        // 使用扩展操作符保留所有原始API属性，只覆盖必要的默认值
        const formattedProducts = rightTableData.value.map(product => ({
            ...product, // 保留所有原始API属性
            // 只覆盖必要的默认值
            num: 0, // 默认出库数量
            unit_price: product.price || 0, // 默认单价
            discount: 0, // 默认折扣
        }));
        
        console.log('选中的产品数据:', formattedProducts);
        
        // 发送格式化的产品数据到父组件
        emit('selectProduct', formattedProducts);
        dialogVisible.value = false;
    } else {
        console.log('没有选择任何产品');
    }
};

const emit = defineEmits(['selectProduct']);

defineExpose({ openLoading });
</script>

<style lang="scss" scoped>
.dialog-content {
    // display: flex;
    // height: 600px;
    // flex-direction: row;
    // gap: 10px;
    height: 100%;
    display: flex;
    gap: 10px;
    overflow: hidden;

    .row-1 {
        flex: 1;
        
        border: 1px solid #f0f0f0;

        .row-1-title {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 16px;
            width: 76%;
            border-bottom: 1px solid #f0f0f0;
            margin: 0 auto;
            color: #172b4d;
        }

        .row-1-content {
            padding: 10px;
            margin: 0 10px;

            &:hover {
                background: #edecff;
                cursor: pointer;
                color: #626aef;
            }
        }
    }

    .row-2 {
        border: 1px solid #f0f0f0;
        display: flex;
        flex-direction: column;
        overflow: hidden;

        .row-2-search {
            padding: 10px;
            width: 50%;
        }

        .table-container {
            flex: 1;
            overflow-y: auto;
            overflow-x: hidden;

            &::-webkit-scrollbar {
                width: 6px;
                height: 6px;
            }

            &::-webkit-scrollbar-thumb {
                border-radius: 3px;
                background: #ddd;
            }

            &::-webkit-scrollbar-track {
                border-radius: 3px;
                background: #f5f5f5;
            }

            .el-table {
                height: 100%;
            }
        }
    }

    .row-3 {
        flex: 2;
        border: 1px solid #f0f0f0;
        overflow: hidden;
        display: flex;
        flex-direction: column;

        .row-head {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 16px;

            .row-head-left {}

            .row-head-right {
                color: #766fff;
                cursor: pointer;
            }
        }
    }
    .table-container {
        flex: 1;
        overflow: auto;
    }
}

// ::v-deep .el-dialog {
//     --el-dialog-padding-primary: 0px;
// }


::v-deep(.el-dialog) {
  margin-top: 40px !important;
  height: calc(100vh - 80px);
  display: flex;
  flex-direction: column;
}

::v-deep .el-dialog__header {
    padding: 10px 16px;
    border-bottom: 1px solid #f0f0f0;
    font-weight: bold;
}

::v-deep .dialog-footer {
    padding: 10px 16px;
    border-top: 1px solid #f0f0f0;
}

::v-deep .el-dialog__headerbtn .el-dialog__close {
    color: #000;
}

// ::v-deep .el-dialog__body {
//     padding: 20px 10px;
// }

/* 2. 表头、表尾固定高，body 吃剩余 */
::v-deep(.el-dialog__body) {
  flex: 1;
  overflow: hidden;          /* 只截断，滚动交给内部 */
  padding: 10px;
}
:deep(.cell) {
    white-space: nowrap;
    text-overflow: ellipsis;
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
    background-color: #6860ff;
    border-color: #6860ff;
}

:deep(.el-checkbox__inner:hover) {
    border-color: #626aef !important;
}

:deep(.el-checkbox__input.is-indeterminate .el-checkbox__inner) {
    background-color: #6860ff;
}

:deep(.el-checkbox__input.is-indeterminate .el-checkbox__inner) {
    border-color: #6860ff;
}
</style>